﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Web.SessionState;
using SZHL.UI.AppCode;

namespace SZHL.UI.API
{
    /// <summary>
    /// FTAPI 的摘要说明
    /// </summary>
    public class WXAPI : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            string strAction = context.Request["Action"] ?? "";
            //string strUserName = context.Request["UserName"] ?? "";

            string P1 = context.Request["P1"] ?? "";
            string P2 = context.Request["P2"] ?? ""; 
            
            Msg_Result Model = new Msg_Result() { Action = strAction.ToUpper(), ErrorMsg = "" };
            if (!string.IsNullOrEmpty(strAction))
            {
                try
                {
                    if (strAction.ToUpper() == "GetUserCodeByCode".ToUpper())
                    {
                        //new SZHL.UI.AppCode.JH_Auth_LogB().Insert(new SZHL.Data.JH_Auth_Log() { CRDate = DateTime.Now, LogContent = "接口调用，action：" + Model.Action   });

                        #region 获取Code
                        Model.ErrorMsg = "获取Code错误，请重试";

                        string strCode = context.Request["code"] ?? "";
                        if (!string.IsNullOrEmpty(strCode))
                        {
                            //获取用户名
                            //string username = new SZHL.UI.AppCode.WXHelp().GetUserDataByCode(strCode, Int32.Parse(SZHL.UI.AppCode.WXHelp.GetWXInfo("appCCQJID")));
                            string username = new SZHL.UI.AppCode.WXHelp().GetUserDataByCode(strCode, 25);

                            if (!string.IsNullOrEmpty(username))
                            {
                                //根据用户名更新Code和时间
                                string strGuid = System.Guid.NewGuid().ToString();
                                var jau = new SZHL.UI.AppCode.JH_Auth_UserB().GetEntity(p => p.UserName == username);
                                if (jau != null)
                                {
                                    jau.mobcode = strGuid;
                                    jau.mobcodedate = DateTime.Now;
                                    if (new SZHL.UI.AppCode.JH_Auth_UserB().Update(jau))
                                    {
                                        Model.ErrorMsg = "";
                                        Model.Result = strGuid;
                                        //Model.Result1 = username;
                                    }
                                }

                            }

                        } 
                        #endregion
                    }
                    else
                    {
                        #region 必须登录执行接口


                        string strUserName = string.Empty;

                        if (context.Request.Cookies["szhlcode"] != null)
                        {
                            //通过Cookies获取Code
                            //string szhlcode = "5ab470be-4988-4bb3-9658-050481b98fca"; 
                            string szhlcode = context.Request.Cookies["szhlcode"].Value.ToString();
                            //通过Code获取用户名，然后执行接口方法
                            var jau = new SZHL.UI.AppCode.JH_Auth_UserB().GetEntity(p => p.mobcode == szhlcode);
                            if (jau != null)
                            {
                                var container = ServiceContainer.Current().Resolve<IWsService>(strAction.ToUpper());
                                JH_Auth_UserB.UserInfo UserInfo = new JH_Auth_UserB.UserInfo(jau.UserName);

                                container.ProcessRequest(context, ref Model, P1, P2, UserInfo);
                            }
                        } 
                        #endregion
                    }

                }
                catch (Exception ex)
                {
                    new SZHL.UI.AppCode.JH_Auth_LogB().Insert(new SZHL.Data.JH_Auth_Log() { CRDate = DateTime.Now, LogContent = "接口出错，action：" + Model.Action+"，错误原因" + ex.Message.ToString() });
                    Model.ErrorMsg = "操作异常，请重试";
                    Model.Result = ex.Message;
                }
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string Result = JsonConvert.SerializeObject(Model, Formatting.Indented, timeConverter).Replace("null", "\"\"");
                context.Response.Write(Result);

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}